from __future__ import division
import sys
import os
import glob

import numpy
import matplotlib.pyplot as plt
import matplotlib.patches as patches

import chdparser


def main(argv=None):
    if argv is None:
        argv = sys.argv
    
    fn = argv[1]
    print 'Graphing data from file {0}'.format(fn),
    with open(fn, 'rb') as f:
        fdat = f.read()
    
    data = chdparser.CHD_Data(fdat)

    # Absorbance graph filter (box)
    AU_BOX_LEN = 13
    au_filter = numpy.ones(AU_BOX_LEN)/AU_BOX_LEN
    au_box_tails = (AU_BOX_LEN-1)/2
    
    # Conductivity graph filter (raised-cosine)
    #cond_filter = numpy.ones(13)/13
    COND_RCF_LEN = 20
    cond_filter = numpy.cos(numpy.pi * numpy.arange(-COND_RCF_LEN,COND_RCF_LEN+1)/COND_RCF_LEN) + 1
    cond_filter = cond_filter/sum(cond_filter)

    au = numpy.convolve(data.au,au_filter,'valid')
    cond = numpy.convolve(data.cond,cond_filter,'valid')
    
    au_color = 'b'
    cond_color = 'r'
    
    fig = plt.figure()
    ax1 = fig.add_subplot(1, 1, 1, axisbg='w')
    ax2 = ax1.twinx()
    
    ax1.plot(data.time[au_box_tails:-au_box_tails], au, au_color)
    #ax1.plot(*(zip(*data.au) + [au_color]))
    ax1.set_xlabel('time (min) / Volume (mL)')
    ax1.set_ylabel('Absorbance (AU)', color=au_color)
    ax1.set_xlim(*data.t_range)
    ax1.set_ylim(*data.au_range)
    for tl in ax1.get_yticklabels():
        tl.set_color(au_color)
       
    '''
    ax1.annotate(
            '99',
            xy=(100, 0.5),  # theta, radius
            xycoords='data',
            xytext=(0, 20),    # fraction, fraction
            textcoords='offset points',
            arrowprops=dict(
                    arrowstyle='->', 
                    connectionstyle='arc3,rad=.2',
                    #facecolor='black', shrink=0.05
                    ),
            horizontalalignment='center',
            verticalalignment='bottom',
            )
    '''
    
    #el = patches.Ellipse((20, -1), 0.5, 0.5)
    #ax1.add_patch(el)
    frac_colors = {
            50: (0.5, 1.0, 0.5),
            10: (0.6, 0.6, 1.0),
            40: (1.0, 0.3, 0.3),
            }
    frac_heights = {
            65535: 45,
            255: 25
            }
    
    for frac in data.fractions[::-1]:
        ax1.annotate(
                frac[0], 
                xy=(frac[3], 0),  
                xycoords='data',
                xytext=(0, frac_heights[frac[1]]), 
                textcoords='offset points',
                size=6, 
                va="center",
                bbox=dict(
                        boxstyle="round", 
                        fc=frac_colors[frac[2]],#(0.6, 0.6, 1.0),
                        ec="none"
                        ),
                arrowprops=dict(
                        arrowstyle="wedge,tail_width=.5",
                        fc=frac_colors[frac[2]],
                        ec="none",
                        patchA=None,
                        #patchB=el,
                        relpos=(0.5, 0.5),
                        ),
                horizontalalignment='center',
                )
    '''
    ax1.annotate(
            '22', 
            xy=(100, 0.5),  
            xycoords='data',
            xytext=(0, 50), 
            textcoords='offset points',
            arrowprops=dict(arrowstyle="->")
        )
        
    ax1.annotate(
            '11', 
            xy=(50, 0),  
            xycoords='data',
            xytext=(0, 50), 
            textcoords='offset points',
            #bbox=dict(
            #        boxstyle="round",
            #        fc="0.8"
            #        ),
            #bbox=patches.Circle(3),
            arrowprops=dict(
                    arrowstyle="-",
                    #connectionstyle="angle,angleA=0,angleB=90,rad=10"
                    ),
            horizontalalignment='center',
            verticalalignment='center',
            )
            
    ax1.annotate(
            'angle', 
            xy=(0, 0), xycoords='data',
            xytext=(-50, 30), textcoords='offset points',            
            bbox=dict(boxstyle="round", fc="0.8"),
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="angle,angleA=0,angleB=90,rad=0"),
            )
    '''
    ax2.plot(data.time[COND_RCF_LEN:-COND_RCF_LEN], cond, cond_color)
    #ax2.plot(*(zip(*data.cond) + [cond_color]))
    ax2.set_ylabel('Conductivity', color=cond_color)
    ax2.set_ylim(*data.cond_range)
    for tl in ax2.get_yticklabels():
        tl.set_color(cond_color)
    
    #fig.show()
    fig.savefig(argv[1] + '.pdf')
    
    #raw_input('Press any key to exit...')
    
        
if __name__ == '__main__':
    sys.exit(main())